from flask import Flask, request, jsonify, send_file
from flask_cors import CORS
import os
import uuid
from datetime import datetime
from pptx import Presentation
from pptx.util import Inches, Pt
from pptx.enum.text import PP_ALIGN
from pptx.dml.color import RGBColor

app = Flask(__name__)
CORS(app)

# 确保临时目录存在
TEMP_DIR = 'temp'
if not os.path.exists(TEMP_DIR):
    os.makedirs(TEMP_DIR)

class PPTGenerator:
    def __init__(self):
        self.prs = Presentation()
        
    def create_title_slide(self, title, subtitle):
        """创建标题页"""
        slide_layout = self.prs.slide_layouts[0]  # 标题幻灯片
        slide = self.prs.slides.add_slide(slide_layout)
        
        title_placeholder = slide.shapes.title
        subtitle_placeholder = slide.placeholders[1]
        
        title_placeholder.text = title
        subtitle_placeholder.text = subtitle
        
        # 设置字体
        for paragraph in title_placeholder.text_frame.paragraphs:
            paragraph.font.size = Pt(44)
            paragraph.font.color.rgb = RGBColor(0, 51, 102)
            
    def create_content_slide(self, title, content, bullet_points=None):
        """创建内容页"""
        slide_layout = self.prs.slide_layouts[1]  # 标题和内容
        slide = self.prs.slides.add_slide(slide_layout)
        
        title_placeholder = slide.shapes.title
        content_placeholder = slide.placeholders[1]
        
        title_placeholder.text = title
        
        text_frame = content_placeholder.text_frame
        text_frame.clear()
        
        if bullet_points:
            for i, point in enumerate(bullet_points):
                if i == 0:
                    p = text_frame.paragraphs[0]
                else:
                    p = text_frame.add_paragraph()
                p.text = point
                p.font.size = Pt(18)
                p.level = 0
        else:
            p = text_frame.paragraphs[0]
            p.text = content
            p.font.size = Pt(18)
            
    def create_welcome_slide(self, visitor_name, position, purpose):
        """创建欢迎页"""
        welcome_text = f"热烈欢迎\n{visitor_name}\n{position}"
        purpose_text = f"来访目的：{self.get_purpose_text(purpose)}"
        self.create_title_slide(welcome_text, purpose_text)
        
    def create_company_overview_slide(self, focus_type):
        """创建公司介绍页"""
        title = "公司介绍"
        
        if focus_type == "overview":
            content = [
                "• 公司成立时间与发展历程",
                "• 核心业务领域",
                "• 组织架构",
                "• 企业文化"
            ]
        elif focus_type == "achievement":
            content = [
                "• 近年业绩亮点",
                "• 重要项目成果",
                "• 市场份额",
                "• 荣誉资质"
            ]
        elif focus_type == "technology":
            content = [
                "• 核心技术优势",
                "• 研发团队规模",
                "• 专利与知识产权",
                "• 技术创新成果"
            ]
        else:  # development
            content = [
                "• 战略发展规划",
                "• 市场拓展计划",
                "• 技术发展方向",
                "• 合作愿景"
            ]
            
        self.create_content_slide(title, "", content)
        
    def create_agenda_slide(self, duration, visitor_type):
        """创建议程页"""
        title = "会议议程"
        
        if visitor_type == "leader":
            if duration <= 30:
                agenda = [
                    "1. 欢迎致辞（5分钟）",
                    "2. 工作汇报（15分钟）",
                    "3. 领导指导（10分钟）"
                ]
            elif duration <= 60:
                agenda = [
                    "1. 欢迎致辞（5分钟）",
                    "2. 工作汇报（20分钟）",
                    "3. 现场参观（20分钟）",
                    "4. 领导指导（15分钟）"
                ]
            else:
                agenda = [
                    "1. 欢迎致辞（5分钟）",
                    "2. 工作汇报（30分钟）",
                    "3. 现场参观（30分钟）",
                    "4. 座谈交流（20分钟）",
                    "5. 领导指导（15分钟）"
                ]
        else:  # guest
            if duration <= 30:
                agenda = [
                    "1. 欢迎介绍（5分钟）",
                    "2. 公司介绍（15分钟）",
                    "3. 交流讨论（10分钟）"
                ]
            elif duration <= 60:
                agenda = [
                    "1. 欢迎介绍（5分钟）",
                    "2. 公司介绍（20分钟）",
                    "3. 现场参观（20分钟）",
                    "4. 合作洽谈（15分钟）"
                ]
            else:
                agenda = [
                    "1. 欢迎介绍（5分钟）",
                    "2. 公司介绍（25分钟）",
                    "3. 现场参观（30分钟）",
                    "4. 技术交流（20分钟）",
                    "5. 合作洽谈（20分钟）"
                ]
                
        self.create_content_slide(title, "", agenda)
        
    def create_interaction_slide(self, visitor_type):
        """创建互动环节页"""
        title = "互动环节"
        
        if visitor_type == "leader":
            content = [
                "• 工作指导与建议",
                "• 发展方向指示",
                "• 问题解答",
                "• 期望与要求"
            ]
        else:
            content = [
                "• 技术问题讨论",
                "• 合作模式探讨",
                "• 商务条款协商",
                "• 后续合作计划"
            ]
            
        self.create_content_slide(title, "", content)
        
    def create_contact_slide(self):
        """创建联系页"""
        title = "联系方式"
        content = [
            "• 联系人：[填写联系人姓名]",
            "• 电话：[填写联系电话]",
            "• 邮箱：[填写联系邮箱]",
            "• 地址：[填写公司地址]"
        ]
        self.create_content_slide(title, "", content)
        
    def get_purpose_text(self, purpose):
        """获取来访目的文本"""
        purpose_map = {
            'inspection': '工作视察',
            'guidance': '工作指导',
            'meeting': '商务洽谈',
            'exchange': '技术交流',
            'cooperation': '合作签约',
            'visit': '参观访问'
        }
        return purpose_map.get(purpose, '来访')
        
    def generate_ppt(self, data):
        """生成完整PPT"""
        visitor_name = data['visitorName']
        position = data['visitorPosition']
        purpose = data['visitPurpose']
        duration = data['duration']
        visitor_type = data['visitorType']
        company_focus = data['companyFocus']
        
        # 1. 欢迎页
        self.create_welcome_slide(visitor_name, position, purpose)
        
        # 2. 议程页
        self.create_agenda_slide(duration, visitor_type)
        
        # 3. 公司介绍
        self.create_company_overview_slide(company_focus)
        
        # 4. 互动环节
        self.create_interaction_slide(visitor_type)
        
        # 5. 联系页
        self.create_contact_slide()
        
        # 生成文件名
        timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
        filename = f"接待PPT_{visitor_name}_{timestamp}.pptx"
        filepath = os.path.join(TEMP_DIR, filename)
        
        # 保存PPT
        self.prs.save(filepath)
        
        return {
            'filename': filename,
            'filepath': filepath,
            'title': f"接待{visitor_name}演示文稿",
            'slideCount': len(self.prs.slides),
            'slides': [
                {'title': '欢迎页', 'description': f'欢迎{visitor_name}{position}'},
                {'title': '会议议程', 'description': f'根据{duration}分钟定制'},
                {'title': '公司介绍', 'description': f'重点介绍{self.get_focus_text(company_focus)}'},
                {'title': '互动环节', 'description': f'针对{visitor_type}的互动安排'},
                {'title': '联系方式', 'description': '后续联系信息'}
            ]
        }
        
    def get_focus_text(self, focus):
        focus_map = {
            'overview': '公司概况',
            'achievement': '业绩展示',
            'technology': '技术实力',
            'development': '发展规划'
        }
        return focus_map.get(focus, '公司情况')

@app.route('/')
def index():
    return send_file('../index.html')

@app.route('/generate-ppt', methods=['POST'])
def generate_ppt():
    try:
        data = request.json
        
        # 验证必填字段
        required_fields = ['visitorType', 'visitorName', 'visitorPosition', 'visitPurpose', 'duration', 'companyFocus']
        for field in required_fields:
            if field not in data or not data[field]:
                return jsonify({'error': f'缺少必填字段: {field}'}), 400
        
        # 生成PPT
        generator = PPTGenerator()
        result = generator.generate_ppt(data)
        
        return jsonify(result)
        
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@app.route('/download/<filename>')
def download_file(filename):
    try:
        filepath = os.path.join(TEMP_DIR, filename)
        if os.path.exists(filepath):
            return send_file(filepath, as_attachment=True)
        else:
            return jsonify({'error': '文件不存在'}), 404
    except Exception as e:
        return jsonify({'error': str(e)}), 500

if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0', port=5000)
